import React, { Component } from 'react';

import { Upload, message, Input } from 'antd';
import Material, { News, Adv } from 'uikit/material';
import Links from 'uikit/links';

import { QMConst } from 'qm-ux';

import addImg from '../../style/imgs/add.png';
import editImg from '../../style/imgs/edit.png';
import mpnewsImg from '../../style/imgs/mpnews.png';
import advImg from '../../style/imgs/adv.png';
import imageImg from '../../style/imgs/image.png';
import voiceImg from '../../style/imgs/voice.png';
import mpvideoImg from '../../style/imgs/mpvideo.png';
import pageImg from '../../style/imgs/page.png';

export default class MassInput extends Component {
  constructor(props) {
    super(props);
    this.state = {
      type: 'text', //['text', 'mpnews', 'news', 'image', 'voice', 'mpvideo', 'page']
      btns: [],
      data: {
        text: '',
        mpnews: null,
        news: null,
        image: null,
        voice: null,
        mpvideo: null,
        page: null
      }
    };
  }

  componentDidMount() {
    this.update('tabs' in this.props ? { tabs: this.props.tabs } : {});
  }

  render() {
    let { textMaxLength } = this.props,
      { type, btns, data } = this.state;

    if (type === 'text') {
      data.text = data.text.substr(0, textMaxLength);
    }

    return (
      <div className="mass-input">
        <div className="mass-head">
          {btns.map(o =>
            <div className={`mass-head-btn${o.type === type ? ' active' : ''}`} onClick={() => this._typeChange(o)}>
              <img src={o.img} />
              <span>{o.text}</span>
            </div>
          )}
        </div>
        <Material ref="material" onSelect={e => this._select(e)} />
        <div className="mass-body">
          {
            {
              text: (
                <div className="mass-text">
                  <Input
                    type="textarea"
                    placeholder="请输入..."
                    maxLength={textMaxLength}
                    value={data.text}
                    onChange={this._textChange}
                  />
                  <div className="mass-text-state">
                    {!textMaxLength || <span>您还可以输入{Math.max(0, textMaxLength - data.text.length)}字</span>}
                  </div>
                </div>
              ),
              mpnews: (
                <div className="mass-mpnews">
                  {data[type]
                    ? <News data={data[type]} onSelect={() => this.refs.material.open('news', data[type])} />
                    : <MassAdd text="从素材库中选择" onClick={() => this.refs.material.open('news')} />}
                </div>
              ),
              news: (
                <div className="mass-news">
                  {data[type]
                    ? <Adv data={data[type]} onSelect={() => this.refs.material.open('adv', data[type])} />
                    : <MassAdd text="从素材库中选择" onClick={() => this.refs.material.open('adv')} />}
                </div>
              ),
              image: (
                <div>
                  {data[type]
                    ? <Image src={data[type].url} onSelect={() => this.refs.material.open('image', data[type])} />
                    : <MassAdd text="从素材库中选择" onClick={() => this.refs.material.open('image')} />}
                  <MassUpload type="image" text="上传图片" maxSize={2*1024*1024} fileExt={'bmp/png/jpeg/jpg/gif'} onSuccess={this._select} />
                </div>
              ),
              voice: (
                <div>
                  <MassAdd text="从素材库中选择" onClick={() => this.refs.material.open('voice')} />
                  <MassUpload type="audio" text="上传音频" maxSize={2*1024*1024} fileExt={'mp3/wma/wav/amr'} onSuccess={this._select} />
                </div>
              ),
              mpvideo: (
                <div>
                  <MassAdd text="从素材库中选择" onClick={() => this.refs.material.open('video')} />
                  <MassUpload type="video" text="上传视频" maxSize={10*1024*1024} fileExt={'mp4'} onSuccess={this._select} />
                </div>
              ),
              page: (
                <div className="mass-page">
                  <Links ref="links" onSelect={this._select} />
                  {data[type]
                    ? <a onClick={() => this.refs.links.open(data[type])}>{(data[type].data || {}).url}</a>
                    : <MassAdd text="从素材库中选择" onClick={() => this.refs.links.open()} />}
                </div>
              )
            }[type]
          }
        </div>
      </div>
    );
  }

  update = ({ type = this.state.type, data, tabs = ['text', 'mpnews', 'news', 'image', 'page'] }) => {
    if (data !== null) {
      this.state.data = Object.assign(
        {
          text: '',
          mpnews: null,
          news: null,
          image: null,
          voice: null,
          mpvideo: null,
          page: null
        },
        { [type]: type === 'text' ? data || '' : data }
      );
    }
    // console.log('update', this.state.data);
    this.setState({
      type: tabs.includes(type) ? type : tabs[0],
      data: this.state.data,
      btns: tabs.reduce((p, type) => {
        return p.push(
          {
            text: { type: 'text', text: '文字', img: editImg },
            mpnews: { type: 'mpnews', text: '图文消息', img: mpnewsImg },
            news: { type: 'news', text: '高级图文', img: advImg },
            image: { type: 'image', text: '图片', img: imageImg },
            voice: { type: 'voice', text: '语音', img: voiceImg },
            mpvideo: { type: 'mpvideo', text: '视频', img: mpvideoImg },
            page: { type: 'page', text: '页面', img: pageImg }
          }[type]
        ), p;
      }, [])
    });
  };

  init = (flag = true) => {
    this.setState({
      type: 'text',
      data: {
        text: '',
        mpnews: null,
        news: null,
        image: null,
        voice: null,
        mpvideo: null,
        page: null
      }
    });
    flag && this.update({});
  };

  _typeChange = ({ type }) => {
    if (type !== this.state.type) {
      this.setState({ type });
      this._change();
    }
  };

  _textChange = ({ target: { value } }) => {
    this.state.data.text = value;
    this.setState({ data: this.state.data });
    this._change();
  };

  _select = e => {
    let { type, data } = this.state;
    data[type] = e;
    this.setState({ data });
    this._change();
  };

  _change = () => {
    setTimeout(() => {
      let { type, data } = this.state,
        { onChange = () => {} } = this.props;
      onChange({ type, data: data[type] });
    }, 1);
  };
}

class Image extends Component {
  render() {
    let { src, onSelect = () => {} } = this.props,
      style = { backgroundImage: `url("${src}")` };

    return <div className="mass-image" style={style} onClick={onSelect} />;
  }
}

class MassAdd extends Component {
  render() {
    let { onClick = () => {} } = this.props;

    return (
      <div className="mass-add" onClick={onClick}>
        <img src={addImg} />
        <div>{this.props.text}</div>
        {this.props.children}
      </div>
    );
  }
}

export class MassUpload extends Component {
  render() {
    let { type, text } = this.props;

    return (
      <Upload
        action={`${QMConst.HOST['v_wx_api']}/api/material/upload`}
        showUploadList={false}
        withCredentials={true}
        accept={type + '/*'}
        name="media"
        data={{
          type: {
            image: 'image',
            audio: 'voice',
            video: 'video'
          }[type]
        }}
        onChange={this._change}
        beforeUpload = {this._beforeUpload}
      >
        {this.props.children || <MassAdd text={text} />}
      </Upload>
    );
  }
	
	_beforeUpload = (file, fileList)=>{
    let type = {
	    image: '图片',
	    audio: '语音',
	    video: '视频',
      def:'文件'
    }[this.props.type || 'def'];
    let {maxSize,fileExt} = this.props;
    let {name,size} = file;
    let fileType = name.split('.')[1];
    if(fileExt && !fileExt.includes(fileType.toLocaleLowerCase())){
      message.warn(`${type}格式不支持${fileType}`);
      return false;
    }
    if(maxSize && size>maxSize){
	    message.warn(`${type}大小超过${maxSize/1024/1024}M`);
	    return false;
    }
    return true;
  };

  _change = ({ file: { response } }) => {
    debugger;
    if (response) {
      let { onSuccess = () => {} } = this.props;
      if (response.errcode) {
        message.error(response.errmsg);
      } else {
        onSuccess(response);
      }
    }
  };
}
